#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Python 3.x
Flask 2.1.3
Flask-Babel 2.0.0

Official Manual Address : https://python-babel.github.io/flask-babel/

"""
from flask import Flask
from flask_babel import Babel, format_datetime, refresh
from flask_babel import format_number, format_decimal, format_currency, format_percent, format_scientific
from flask_babel import gettext, ngettext, lazy_gettext
from datetime import datetime

app = Flask(__name__)
# 初始化插件
babel = Babel()
babel.init_app(app=app)


@app.route("/format_datetime_eg")
def format_datetime_eg():
    """
    格式化日期
    :return:
    """
    print(format_datetime(datetime(1987, 3, 5, 17, 12)))
    # > Mar 5, 1987, 5:12:00 PM
    print(format_datetime(datetime(1987, 3, 5, 17, 12), 'full'))
    # > Thursday, March 5, 1987 at 5:12:00 PM Coordinated Universal Time
    print(format_datetime(datetime(1987, 3, 5, 17, 12), 'short'))
    # > 3/5/87, 5:12 PM
    print(format_datetime(datetime(1987, 3, 5, 17, 12), 'dd mm yyy'))
    # > 05 12 1987
    print(format_datetime(datetime(1987, 3, 5, 17, 12), 'dd mm yyyy'))
    # > 05 12 1987
    # 切换语言
    app.config["BABEL_DEFAULT_LOCALE"] = "zh_CN"
    refresh()
    print(format_datetime(datetime(1987, 3, 5, 17, 12), 'full'))
    # > 1987年3月5日星期四 协调世界时 17:12:00


@app.route("/format_number_eg")
def format_number_eg():
    """
    格式化数字
    :return:
    """
    print(format_number(1099))
    # > 1,099
    print(format_decimal(1.2346))
    # > 1.235
    print(format_currency(1099.98, 'USD'))
    # > $1,099.98
    print(format_percent(0.34))
    # > 34%
    print(format_scientific(10000))
    # > 1E4
    # 切换语言
    app.config["BABEL_DEFAULT_LOCALE"] = "zh_CN"
    refresh()
    print(format_number(1099))
    # > 1,099
    print(format_decimal(1.2346))
    # > 1.235
    print(format_currency(1099.98, 'USD'))
    # > US$1,099.98
    print(format_percent(0.34))
    # > 34%
    print(format_scientific(10000))
    # > 1E4


@app.route("/using_translations")
def using_translations():
    """
    gettext：翻译单数字符串
    ngettext：翻译可以变成复数的字符串
    :return:
    """
    print(gettext(u'A simple string'))
    # > A simple string
    print(gettext(u'Value: %(value)s', value=42))
    # > Value: 42
    print(ngettext(u'%(num)s Apple', u'%(num)s Apples', 2))
    # > 2 Apples


if __name__ == '__main__':
    app.run()
